package com.example.myapplication.mylivedata;

import androidx.lifecycle.MutableLiveData;

import java.util.HashMap;
import java.util.Map;

public class LiveDataBus {

    // 保存订阅者
    private Map<String, MutableLiveData<Object>> bus;
    private LiveDataBus liveDataBus;

    public LiveDataBus() {
        bus = new HashMap<>();
    }

    public LiveDataBus getLiveDataBus() {
        if (liveDataBus == null) {
            synchronized (LiveDataBus.class) {
                if (liveDataBus == null) {
                    liveDataBus = new LiveDataBus();
                }
            }
        }
        return liveDataBus;
    }

    /**
     *
     * @param key  key
     * @param type  传入的数据类型
     * @param sticky  是否创建有粘性事情的 LiveData
     * @return
     * @param <T>   返回来传进来的  type  数据类型
     */
    public synchronized <T> MutableLiveData<T> with(String key, Class<T> type, boolean sticky) {
        if (!bus.containsKey(key)) {
            if (sticky) {
                bus.put(key, new MutableLiveData<>());
            } else {
                bus.put(key, new NonStickyMutableLiveData<>());
            }
        }
        return (MutableLiveData<T>) bus.get(key);
    }

}
